package com.jn.okhttp.views;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jn.okhttp.R;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.net.URLEncoder;

public class TranslationActivity extends AppCompatActivity {

    private static final String TAG = "TranslationActivity";
    private EditText inputText;
    private TextView translationResult;
    private Button translateButton, backButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_translation);

        inputText = findViewById(R.id.input_text);
        translationResult = findViewById(R.id.translation_result);
        translateButton = findViewById(R.id.button_translate);
        backButton = findViewById(R.id.button_back_to_main);

        translateButton.setOnClickListener(v -> {
            String textToTranslate = inputText.getText().toString();
            if (!textToTranslate.isEmpty()) {
                translate(textToTranslate);
            } else {
                translationResult.setText("请输入要翻译的文本");
            }
        });

        backButton.setOnClickListener(v -> finish());
    }

    private void translate(String text) {
        String url;

        try {
            // 简单判断输入内容是中文还是英文
            if (text.matches(".*[\\u4e00-\\u9fa5]+.*")) { // 检测中文字符
                // 汉 -> 英
                url = "https://api.oioweb.cn/api/txt/QQFanyi?sourceText=" + URLEncoder.encode(text, "UTF-8") + "&from=zh&to=en";
            } else {
                // 英 -> 汉
                url = "https://api.oioweb.cn/api/txt/QQFanyi?sourceText=" + URLEncoder.encode(text, "UTF-8") + "&from=en&to=zh";
            }
        } catch (Exception e) {
            Log.e(TAG, "编码失败: ", e);
            return;
        }

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "翻译请求失败: ", e);
                runOnUiThread(() -> translationResult.setText("请求失败，请稍后重试。"));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    Log.d(TAG, "返回的数据: " + responseData);
                    parseTranslationJson(responseData);
                } else {
                    Log.e(TAG, "翻译请求失败: " + response.message());
                    runOnUiThread(() -> translationResult.setText("翻译请求失败，请稍后重试。"));
                }
            }
        });
    }

    private void parseTranslationJson(String jsonData) {
        try {
            Gson gson = new Gson();
            JsonObject jsonObject = JsonParser.parseString(jsonData).getAsJsonObject();

            if (jsonObject.get("code").getAsInt() == 200) { // 检查码为 200
                JsonObject result = jsonObject.getAsJsonObject("result");

                if (result != null) {
                    String targetText = result.get("targetText").getAsString();
                    runOnUiThread(() -> translationResult.setText(targetText));
                } else {
                    Log.d(TAG, "翻译失败或无结果");
                    runOnUiThread(() -> translationResult.setText("翻译失败或无结果"));
                }
            } else {
                Log.d(TAG, "请求失败，状态码: " + jsonObject.get("code").getAsInt());
                runOnUiThread(() -> translationResult.setText("翻译请求失败，状态码: " + jsonObject.get("code").getAsInt()));
            }
        } catch (Exception e) {
            Log.e(TAG, "解析翻译 JSON 失败: ", e);
            runOnUiThread(() -> translationResult.setText("解析结果失败，请检查输入。"));
        }
    }
}
